package com.simon.annual.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.simon.annual.entity.ReportAtxnOccasional;
import com.simon.annual.entity.ReportAtxnRoutine;
import com.simon.annual.entity.ReportExpropriation;
import com.simon.annual.entity.ReportGuarantee;
import com.simon.annual.entity.ReportLawsuit;
import com.simon.annual.entity.ReportNeeq;
import com.simon.annual.entity.ReportRestrictedasset;
import com.simon.annual.repositoy.IReportAtxnOccasionalRepositoy;
import com.simon.annual.repositoy.IReportAtxnRoutineRepositoy;
import com.simon.annual.repositoy.IReportExpropriationRepositoy;
import com.simon.annual.repositoy.IReportGuaranteeRepositoy;
import com.simon.annual.repositoy.IReportLawsuitRepositoy;
import com.simon.annual.repositoy.IReportNeeqRepositoy;
import com.simon.annual.repositoy.IReportRestrictedassetRepositoy;
import com.simon.annual.service.ICompanyPublicInfo;
import com.simon.annual.service.IMajorIssues;

/**
 * 第五节:重要事项
 * */
@Service
public class FindMajorIssuesImpl implements IMajorIssues{

	@Resource
	private ICompanyPublicInfo cmpanyPublicInfo;
	@Resource
	private IReportRestrictedassetRepositoy reportRestrictedassetRepositoy;
	@Resource
	private IReportAtxnRoutineRepositoy reportAtxnRoutineRepositoy;
	@Resource
	private IReportLawsuitRepositoy reportLawsuitRepositoy;
	@Resource
	private IReportGuaranteeRepositoy reportGuaranteeRepositoy;
	@Resource
	private IReportExpropriationRepositoy reportExpropriationRepositoy;
	@Resource
	private IReportAtxnOccasionalRepositoy reportAtxnOccasionalRepositoy;
	@Resource
	private IReportNeeqRepositoy reportNeeqRepositoy;
	@Resource
	private Environment env;
	
	@Override
	public ReportNeeq analysis(Document doc, ReportNeeq reportNeeq, int companyPtrId) {
		
		Element  els = doc.getElementsMatchingOwnText(env.getProperty("pdf.five.index")).last();
		if(els!=null){
			//第一节：重要事项索引
			Element major = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.no"), els, 0);
			//处理黏连部分
			while(true){
				Element tag = major.nextElementSibling();
				if(tag.tagName().equals("table")){
					Elements trs =tag.select("tr");
					if(trs.last().children().size()==3&&trs.last().children().get(1).getElementsMatchingOwnText(env.getProperty("pdf.five.yes.no")).hasText()){
						major.append(tag.html());
						tag.remove();
					}else{
						break;
					}
				}else{
					break;
				}
			}		
			Elements majorTd = major.select("tr > *");
			
			//是否存在重大诉讼、仲裁事项
			reportNeeq.setHasMajorLawsuit(majorTd.get(4).text());
			reportNeeq.setMajorLawsuitIndex(majorTd.get(5).text());
			if(majorTd.get(5).text().length()>1&&majorTd.get(4).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.major.value"), major, -15);
				Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
				Elements majorContents = majorContent.select("table tr");
				List<ReportLawsuit> reportLawsuitList = new ArrayList<ReportLawsuit>();
				for (int i = 1; i < majorContents.size()-1; i++) {
					Elements tds = majorContents.get(i).children();
					if(tds.size()==5){
						ReportLawsuit reportLawsuit = new ReportLawsuit();
						reportLawsuit.setName(tds.get(0).text());
						reportLawsuit.setValueInvolved(tds.get(1).text());
						reportLawsuit.setPct_NA(tds.get(2).text());
						reportLawsuit.setIsFinished(tds.get(3).text());
						reportLawsuit.setDisclosureDate(tds.get(4).text());
						reportLawsuit.setProjectScopeId(companyPtrId);
						reportLawsuitList.add(reportLawsuit);
					}
				}
				reportLawsuitRepositoy.save(reportLawsuitList);
				reportNeeq.setLawsuitReview(cmpanyPublicInfo.findNextTag("table",majorContent).text());
			}
			//是否存在对外担保事项
			reportNeeq.setHasExternalGuarantee(majorTd.get(7).text());
			reportNeeq.setExternalGuaranteeIndex(majorTd.get(8).text());
			//
			major = major.nextElementSibling();
			
			if(majorTd.get(8).text().length()>1&&majorTd.get(7).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.guarantee.value"), major, -50);
				Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
				Elements majorContents = majorContent.select("table tr");
				List<ReportGuarantee> reportGuaranteeList = new ArrayList<ReportGuarantee>();
				for (int i = 0; i < majorContents.size()-1; i++) {
					if(i!=0){
						Elements tds = majorContents.get(i).children();
						ReportGuarantee reportGuarantee = new ReportGuarantee();
						reportGuarantee.setObject(tds.get(0).text());
						reportGuarantee.setValue(tds.get(1).text());
						reportGuarantee.setType(tds.get(2).text());
						reportGuarantee.setResponsibility(tds.get(3).text());
						reportGuarantee.setIsProcedureLegitimate(tds.get(4).text());
						reportGuarantee.setIsAffiliated(tds.get(5).text());
						reportGuarantee.setProjectScopeId(companyPtrId);
						reportGuaranteeList.add(reportGuarantee);
					}
				}
				reportGuaranteeRepositoy.save(reportGuaranteeList);
				//对外担保分类汇总
				Element guaranty = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.guaranty.external"), ins, -5);
				if(guaranty!=null){
					Element guarantyValue = cmpanyPublicInfo.findNextTag("table", guaranty);
					Elements tds = guarantyValue.select("table tr > *");
					reportNeeq.setExternalGuarantyValue(tds.get(3).text());
					reportNeeq.setGuarantyForShareholderOrControllerValue(tds.get(5).text());
					reportNeeq.setGuranty_for_high_ALR_value(tds.get(7).text());
					reportNeeq.setGuaranty_over_half_NA(tds.get(9).text());
				}
				//清偿情况
				Element payOff = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.guarantee.payoff"), ins, -8);
				if(payOff!=null){
					Element payOffReview = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.guarantee.payoff.end"), payOff, "",0);
					reportNeeq.setGuaranteePayOffReview(payOffReview.text());
				}
			}
			//是否存在控股股东、实际控制人及其关联方占用或转移公司资金、资产的情况
			reportNeeq.setHasExpropriation(majorTd.get(10).text());
			reportNeeq.setExpropriationIndex(majorTd.get(11).text());
			if(majorTd.get(11).text().length()>1&&majorTd.get(10).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.expropriation.obj"), major, -100);
				Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
				Elements majorContents = majorContent.select("table tr");
				List<ReportExpropriation> reportExpropriationList = new ArrayList<ReportExpropriation>();
				for (int i = 1; i < majorContents.size()-1; i++) {
					Elements tds = majorContents.get(i).children();
					if(tds.size()==6){
						ReportExpropriation reportExpropriation = new ReportExpropriation();
						reportExpropriation.setOccupant(tds.get(0).text());
						reportExpropriation.setAsset(tds.get(1).text());
						reportExpropriation.setBgnBalance(tds.get(2).text());
						reportExpropriation.setAccumAmount(tds.get(3).text());
						reportExpropriation.setEndBalance(tds.get(4).text());
						reportExpropriation.setEndBalance(tds.get(5).text());
						reportExpropriation.setProjectScopeId(companyPtrId);
						reportExpropriationList.add(reportExpropriation);
					}
				}
				reportExpropriationRepositoy.save(reportExpropriationList);
				//占用原因、归还及整改情况：
				Element b = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.expropriation.b"), ins, 0);
				if(b!=null){
					Element bend = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.expropriation.b.end"), b, "",0);
					reportNeeq.setExpropriationReview(bend.text());
				}
			}
			//是否存在日常性关联交易事项
			reportNeeq.setHasRoutineAffiliateTxn(majorTd.get(13).text());
			reportNeeq.setRoutineAffiliateTxnIndex(majorTd.get(14).text());
			if(majorTd.get(14).text().length()>1&&majorTd.get(13).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){			
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.routine"), major, -150);
				if(ins!=null){
					Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
					Elements majorContents = majorContent.select("table tr");
					List<ReportAtxnRoutine> reportAtxnRoutineList = new ArrayList<ReportAtxnRoutine>();
					List<ReportAtxnOccasional> reportAtxnOccasionalList = new ArrayList<ReportAtxnOccasional>();
					for (int i = 2; i < majorContents.size()-2; i++) {
						Elements tds = majorContents.get(i).children();
						if(tds.size()==3){
							ReportAtxnRoutine reportAtxnRoutine = new ReportAtxnRoutine();
							reportAtxnRoutine.setName(tds.get(0).text());
							reportAtxnRoutine.setPredictedAmount(tds.get(1).text());
							reportAtxnRoutine.setActualAmount(tds.get(2).text());
							reportAtxnRoutine.setProjectScopeId(companyPtrId);
							reportAtxnRoutineList.add(reportAtxnRoutine);
						}
						if(tds.size()==4){
							//偶发性关联交易的必要性、持续性以及对公司生产经营的影响
							ReportAtxnOccasional reportAtxnOccasional = new ReportAtxnOccasional();
							reportAtxnOccasional.setAffParty(tds.get(0).text());
							reportAtxnOccasional.setContent(tds.get(1).text());
							reportAtxnOccasional.setTxnAmount(tds.get(2).text());
							reportAtxnOccasional.setIsProcedureLegitimate(tds.get(3).text());
							reportAtxnOccasional.setProjectScopeId(companyPtrId);
							reportAtxnOccasionalList.add(reportAtxnOccasional);
						}
					}
					reportAtxnRoutineRepositoy.save(reportAtxnRoutineList);
					reportAtxnOccasionalRepositoy.save(reportAtxnOccasionalList);
				}
			}
			int index =0;
			//处理2016年报表新增偶发性关联交易单独列
			if(majorTd.size()==36||majorTd.size()==42){
				index =3;
				//偶发性关联交易的必要性、持续性以及对公司生产经营的影响
				reportNeeq.setHasRoutineAccidentalTxn(majorTd.get(16).text());
				reportNeeq.setRoutineAccidentalTxnIndex(majorTd.get(17).text());
				if(majorTd.get(17).text().length()>1&&majorTd.get(16).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){			
					Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.routine"), major, -150);
					if(ins!=null){
						Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
						Elements majorContents = majorContent.select("table tr");
						List<ReportAtxnOccasional> reportAtxnOccasionalList = new ArrayList<ReportAtxnOccasional>();
						for (int i = 2; i < majorContents.size()-2; i++) {
							Elements tds = majorContents.get(i).children();
							ReportAtxnOccasional reportAtxnOccasional = new ReportAtxnOccasional();
							reportAtxnOccasional.setAffParty(tds.get(0).text());
							reportAtxnOccasional.setContent(tds.get(1).text());
							reportAtxnOccasional.setTxnAmount(tds.get(2).text());
							reportAtxnOccasional.setIsProcedureLegitimate(tds.get(3).text());
							reportAtxnOccasional.setProjectScopeId(companyPtrId);
							reportAtxnOccasionalList.add(reportAtxnOccasional);
						}
						reportAtxnOccasionalRepositoy.save(reportAtxnOccasionalList);
					}
				}
			}
			
			//是否存在经股东大会审议过的收购、出售资产事项
			reportNeeq.setHasDeliberatedAssetReorganizations(majorTd.get(16+index).text());
			reportNeeq.setDeliberatedAssetReorganizationsIndex(majorTd.get(17+index).text());
			if(majorTd.get(17+index).text().length()>1&&majorTd.get(16+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.asset"), major, -200);
				Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.asset.end"), ins, "",0);
				reportNeeq.setDeliberatedAssetReorganizationsReview(majorContent.text());
			}
			//2016年报无对外投资收购单独项目
			if(majorTd.size()==36||majorTd.size()==42){
				index=-3;
			}else{
				//是否存在经股东大会审议过的对外投资事项
				reportNeeq.setHasDeliberatedInvestement(majorTd.get(19).text());
				reportNeeq.setDeliberatedInvestementIndex(majorTd.get(20).text());
				if(majorTd.get(20).text().length()>1&&majorTd.get(19+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
					Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.investement"), major, -200);
					Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.investement.end"), ins, "",0);
					reportNeeq.setDeliberatedInvestementReview(majorContent.text());
				}
				
				//是否存在经股东大会审议过的企业合并事项
				reportNeeq.setHasDeliberatedConsolidation(majorTd.get(22+index).text());
				reportNeeq.setDeliberatedConsolidationIndex(majorTd.get(23).text());
				if(majorTd.get(23+index).text().length()>1&&majorTd.get(22+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
					Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.comp"), major, -200);
					Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.comp.end"), ins, "",0);
					reportNeeq.setDeliberatedConsolidationReview(majorContent.text());
				}
			}
			//是否存在股权激励事项
			reportNeeq.setHasEquityIncentive(majorTd.get(25+index).text());
			reportNeeq.setEquityIncentiveIndex(majorTd.get(26+index).text());
			if(majorTd.get(26+index).text().length()>1&&majorTd.get(25+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.equity"), major, -200);
				Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.equity.end"), ins, "",0);
				reportNeeq.setEquityIncentiveReview(majorContent.text());
			}
			//是否存在已披露的承诺事项
			reportNeeq.setHasCommitment(majorTd.get(28+index).text());
			reportNeeq.setCommitmentIndex(majorTd.get(29+index).text());
			if(majorTd.get(29+index).text().length()>1&&majorTd.get(28+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.commitment"), major, -200);
				Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.commitment.end"), ins, "",0);
				reportNeeq.setCommitmentReview(majorContent.html());
			}
			//是否存在资产被查封、扣押、冻结或者被抵押、质押的情况
			reportNeeq.setHasRestrictedAsset(majorTd.get(31+index).text());
			reportNeeq.setRestrictedAssetIndex(majorTd.get(32+index).text());
			if(majorTd.get(32+index).text().length()>1&&majorTd.get(31+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.restricte"), major, -200);
				Element majorContent = cmpanyPublicInfo.getNextTag(ins, ins);
				Elements majorContents = majorContent.select("table tr");
				List<ReportRestrictedasset> reportRestrictedassetList = new ArrayList<ReportRestrictedasset>();
				for (int i = 1; i < majorContents.size()-1; i++) {
						Elements tds = majorContents.get(i).children();
						if(tds.size()==5){
							ReportRestrictedasset reportRestrictedasset = new ReportRestrictedasset();
							reportRestrictedasset.setAsset(tds.get(0).text());
							reportRestrictedasset.setRestrictionType(tds.get(1).text());
							reportRestrictedasset.setBookValue(tds.get(2).text());
							reportRestrictedasset.setReason(tds.get(4).text());
							reportRestrictedasset.setProjectScopeId(companyPtrId);
							reportRestrictedassetList.add(reportRestrictedasset);
						}
				}
				reportRestrictedassetRepositoy.save(reportRestrictedassetList);
			}
			//是否存在被调查处罚的事项
			reportNeeq.setHasPenalty(majorTd.get(34+index).text());
			reportNeeq.setPenaltyIndex(majorTd.get(35+index).text());
			if(majorTd.get(35+index).text().length()>1&&majorTd.get(34+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
				Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.penalty"), major, -200);
				Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.penalty.end"), ins, "",0);
				reportNeeq.setPenaltyReview(majorContent.text());
			}
			//2016年报无重大资产重组和媒体质疑事项
			if(majorTd.size()==36){
				index+=-6;
			}else if(majorTd.size()==42){
				
			}else{
				//是否存在重大资产重组的事项
				reportNeeq.setHasAssetsReorganization(majorTd.get(37).text());
				reportNeeq.setAssetsReorganizationIndex(majorTd.get(38).text());
				if(majorTd.get(38).text().length()>1&&majorTd.get(37).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
					Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.reorganization"), major, -200);
					Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.reorganization.end"), ins, "",0);
					reportNeeq.setAssetsReorganizationReview(majorContent==null?"":majorContent.text());
				}
				if(majorTd.size()>40){
					//是否存在媒体普遍质疑的事项
					reportNeeq.setHasMediaQuestioned(majorTd.get(40).text());
					reportNeeq.setMediaQuestionedIndex(majorTd.get(41).text());
					if(majorTd.get(41).text().length()>1&&majorTd.get(40).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
						Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.media"), major, -200);
						Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.five.media.end"), ins, "",0);
						reportNeeq.setMediaQuestionedReview(majorContent.text());
					}
				}
			}
			if(majorTd.size()>43+index){
				//是否存在自愿披露的重要事项
				reportNeeq.setHasVoluntaryDisclosureKeyIssue(majorTd.get(43+index).text());
				reportNeeq.setVoluntaryDisclosureKeyIssueIndex(majorTd.get(44+index).text());
				if(majorTd.get(44+index).text().length()>1&&majorTd.get(43+index).getElementsMatchingOwnText(env.getProperty("pdf.five.yes")).hasText()){
					Element ins = cmpanyPublicInfo.findNextByChar(env.getProperty("pdf.five.disclosure"), major, -200);
					Element majorContent = cmpanyPublicInfo.findEndByChar(env.getProperty("pdf.six"), ins, "",0);
					reportNeeq.setPenaltyReview(majorContent.text());
				}
			}
		}
		return reportNeeqRepositoy.save(reportNeeq);
	}
	
	/**
	 * 合并table换行
	 * */
	private Element buildMeet(Element newElement){
		Elements tbodys = newElement.select("tbody");
		//合并分页table
		if(tbodys.size()>0){
			for (int i = 0; i < tbodys.size()-1; i++) {
				Element body = tbodys.get(i+1);
				//去除多余的合并内容
				if(body.getElementsMatchingOwnText(env.getProperty("pdf.two")).hasText()){
					while(i+1<tbodys.size()){
						tbodys.get(i+1).remove();
						i++;
					}
					return newElement;
				}
				Elements  element = body.select("tr");
				if(!element.isEmpty()){
					boolean ps = element.first().children().size()==tbodys.get(i).select("tr").last().children().size();
					if(ps&&!body.select("tr").first().children().first().hasText()){
						Elements eTd = element.first().children();
						for (int j = 0; j < eTd.size(); j++) {
							tbodys.get(i).select("tr").last().child(j).appendText(eTd.get(j).text());
						}
						element.first().remove();
						if(!tbodys.get(i+1).hasText()){
							tbodys.remove(i+1);
						}
					}
				}
			}
		}
		return newElement;
	}
}
